package com.css.dzj.dzjfxyj.modules.over.service.impl;

import com.css.dzj.dzjfxyj.common.util.Constant;
import com.css.dzj.dzjfxyj.common.util.R;
import com.css.dzj.dzjfxyj.common.util.ServiceUtil;
import com.css.dzj.dzjfxyj.modules.acquier.entity.JgFxyjWarningSignalEntity;
import com.css.dzj.dzjfxyj.modules.acquier.entity.QJgFxyjWarningSignalEntity;
import com.css.dzj.dzjfxyj.modules.distribute.entity.JgFxyjFenfaEntity;
import com.css.dzj.dzjfxyj.modules.distribute.entity.QJgFxyjFenfaEntity;
import com.css.dzj.dzjfxyj.modules.distribute.service.DistributeService;
import com.css.dzj.dzjfxyj.modules.over.mapper.OverMapper;
import com.css.dzj.dzjfxyj.modules.over.service.OverServcie;
import com.css.dzj.dzjfxyj.modules.reply.entitiy.JgFxyjFeedbackEntity;
import com.css.dzj.dzjfxyj.modules.reply.entitiy.QJgFxyjFeedbackEntity;
import com.css.dzj.dzjfxyj.modules.reply.vo.ReplyVo.MainDistributeVo;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class OverServiceImpl implements OverServcie {
    @Autowired
    OverMapper overMapper;
    @Autowired
    DistributeService distributeService;
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    private HttpServletRequest request;
    @Override
    public QueryResults<MainDistributeVo> getPage(Pageable pageable, String fxyjDomainId, String fxyjTitle, String fxyjLevel, String fxyjObjectName, String startTime, String endTime, String startTime1, String endTime1) {

        QJgFxyjWarningSignalEntity q=QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        QJgFxyjFenfaEntity fenfa = QJgFxyjFenfaEntity.jgFxyjFenfaEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (fxyjDomainId == null || fxyjDomainId.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjDomainId.eq(fxyjDomainId.trim()));
        predicate = (fxyjTitle == null || fxyjTitle.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjTitle.like("%" + fxyjTitle.trim() + "%"));
        predicate = (fxyjLevel == null || fxyjLevel.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjLevel.eq(fxyjLevel));
        predicate = (fxyjObjectName == null || fxyjObjectName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjObjectName.like("%"+fxyjObjectName.trim()+"%"));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime + " 00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            Calendar c = Calendar.getInstance();
            try {
                startDate = sf.parse(startTime + " 00:00:00.000");
                endDate = sf.parse(endTime + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.between(startDate,endDate));
        }

        if((StringUtils.isEmpty(startTime1))&&(!StringUtils.isEmpty(endTime1))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime1 + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.dispenseTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime1))&&(StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime1 + " 00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.dispenseTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime1))&&(!StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime1 + " 00:00:00.000");
                endDate = sf.parse(endTime1 + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.dispenseTime.between(startDate,endDate));
        }
        //获取当前登录人机构
        String orgName = ServiceUtil.getOrgName(request);
        predicate = ExpressionUtils.and(predicate,fenfa.fenfaToOrg.eq(orgName));
        //分发表里的回复为未回复，代表当前登录用户没有进行回复操作
        predicate = ExpressionUtils.and(predicate,fenfa.revertState.isNull());
        //分发表里的结束为未结束，代表当前登录用户没有进行结束操作
//        predicate = ExpressionUtils.and(predicate,fenfa.overState.isNull());
        //主表，已认领
        predicate = ExpressionUtils.and(predicate,q.getState.eq(Constant.YIGET));
        //主表，已分发
        predicate = ExpressionUtils.and(predicate,q.dispenseState.eq(Constant.YIDISTRIBUTE));
        return jpaQueryFactory
                .select(Projections.bean(MainDistributeVo.class,
                        q.id,q.fxyjId,q.fxyjDomainId,q.fxyjModelId,q.fxyjAreaNumber,q.fxyjObjectType,q.fxyjObjectId
                        ,q.fxyjObjectName,q.fxyjPlatform,q.fxyjWeb,q.fxyjTransmitTime,q.yjbSendTime,q.getTime,q.operatePerson,q.disposeResult
                        ,q.disposeExplain,q.getState,q.dispenseState,q.dispensePerson,q.dispenseOrg
                        ,q.dispenseTime,q.createTime,q.createPreson,q.updateTime,q.updatePerson,q.operateOrg,q.fxyjTitle
                        ,q.fxyjLevel,q.fxyjAreaName,q.fxyjProps,q.fxyjDetailUrl,q.fxyjOthers,q.fxyjTime,q.fxyjDesc,q.dealState
                        ,fenfa.fenfaToOrg,fenfa.getId,fenfa.overState,fenfa.revertState))
                .from(q)
                .innerJoin(fenfa).on(fenfa.getId.eq(q.id)).
                where(predicate).
                orderBy(q.createTime.desc()).
                offset(pageable.getOffset()).
                limit(pageable.getPageSize()).
                fetchResults();

    }
    //结束操作
    @Override
    @Transactional
    public R saveOver(JgFxyjFeedbackEntity jgFxyjFeedbackEntity, String id,HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(jgFxyjFeedbackEntity)) {
                throw new RuntimeException("新增不能为空");
            }
            String orgName = ServiceUtil.getOrgName(request);
            JgFxyjFenfaEntity jgFxyjFenfaEntity = distributeService.findByGetIdAndFenfaToOrg(id, orgName);
            //jgFxyjFeedbackEntity.setCreatePreson(ServiceUtil.getLoginName(request));
            jgFxyjFeedbackEntity.setCreateTime(new Date());
            //存储分办Id
            jgFxyjFeedbackEntity.setFbId(jgFxyjFenfaEntity.getId());
            //更新主表的处置状态和结束状态
            update(id);
            //获取当前登录人机构
            updateFenFa(id,orgName);
            overMapper.save(jgFxyjFeedbackEntity);
            return R.ok();
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
    //根据主表id查找主表信息
    @Override
    public JgFxyjWarningSignalEntity findById(String id) {
        QJgFxyjWarningSignalEntity q=QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        return jpaQueryFactory.selectFrom(q).where(q.id.eq(id)).fetchOne();
    }
    //根据主表Id查找分办信息表
    @Override
    public List<JgFxyjFenfaEntity> findDistrById(String id) {
        QJgFxyjFenfaEntity q=QJgFxyjFenfaEntity.jgFxyjFenfaEntity;
        return jpaQueryFactory.selectFrom(q).where(q.getId.eq(id)).fetch();
    }

    //根据分办表Id查找结束信息
    @Override
    public JgFxyjFeedbackEntity findFeebackById(String id) {
        QJgFxyjFeedbackEntity q=QJgFxyjFeedbackEntity.jgFxyjFeedbackEntity;
        return jpaQueryFactory.selectFrom(q).where(q.fbId.eq(id)).fetchOne();
    }
    //更新主表的处置状态和结束状态
    @Override
    @Transactional
    public R update(String id) {
        QJgFxyjWarningSignalEntity q=QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        jpaQueryFactory.update(q).set(q.overState,Constant.YIOVER).set(q.dealState,Constant.YIJIESHU).where(q.id.eq(id)).execute();
        return R.ok();
    }
    public R updateFenFa(String id,String orgName) {
        QJgFxyjFenfaEntity q=QJgFxyjFenfaEntity.jgFxyjFenfaEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ExpressionUtils.and(predicate,q.getId.eq(id));
        predicate = ExpressionUtils.and(predicate,q.fenfaToOrg.eq(orgName));
        jpaQueryFactory.update(q)
                .set(q.overState,Constant.YIOVER)
                .where(predicate)
                .execute();
        return R.ok();
    }

}
